<template>
  <div class="review-center">
    <div class="page-header">
      <h1 class="page-title">审核中心</h1>
      <div class="header-actions">
        <el-button type="primary" @click="fetchProjects">刷新</el-button>
      </div>
    </div>

    <el-card>
             <div class="filter-bar">
         <el-select v-model="filterStatus" placeholder="审核状态" style="width: 140px;" clearable @change="handleFilterChange">
           <el-option label="全部" value="" />
           <el-option label="申报中" value="申报中" />
           <el-option label="结题审核中" value="结题审核中" />
         </el-select>
         
                   <el-select v-model="filterProjectCategory" placeholder="请选择项目种类" style="width: 200px;" @change="handleFilterChange">
            <el-option label="教学项目" value="teaching" />
            <el-option label="科研项目" value="research" />
            <el-option label="学术成果" value="academic" />
          </el-select>
         
         <div class="filter-summary">
           <el-tag type="info" size="small">
             共 {{ projects.length }} 个项目待审核
             <span v-if="filterProjectCategory.value">（{{ getProjectCategoryName(filterProjectCategory.value) }}）</span>
           </el-tag>
           <el-button size="small" style="margin-left: 8px;" @click="clearFilters">清除筛选</el-button>
         </div>
       </div>

       <!-- 项目种类说明 -->
       <div v-if="filterProjectCategory.value && projects.length === 0" class="project-category-info">
         <el-alert
           :title="`${getProjectCategoryName(filterProjectCategory.value)}暂无待审核项目`"
           type="info"
           :closable="false"
           show-icon>
           <template #default>
             <p>当前选择的项目种类"{{ getProjectCategoryName(filterProjectCategory.value) }}"暂无需要审核的项目。</p>
             <p>请选择其他项目种类或等待新的项目提交。</p>
           </template>
         </el-alert>
       </div>

       <el-table :data="projects" stripe v-loading="loading">
         <el-table-column prop="leaderName" label="负责人" width="100" show-overflow-tooltip />
         <el-table-column prop="name" label="项目名称" min-width="200" show-overflow-tooltip />
                  <el-table-column prop="projectType" label="项目类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getProjectTypeTagType(row.projectType)" size="small">
                {{ row.projectType || '-' }}
              </el-tag>
            </template>
          </el-table-column>
         <el-table-column prop="level" label="项目级别" width="100" />
        <el-table-column prop="totalFunding" label="经费总额(万元)" width="140">
          <template #default="{ row }">
            {{ row.totalFunding ? (row.totalFunding / 10000).toFixed(2) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始时间" width="120" />
        <el-table-column prop="endDate" label="结束时间" width="120" />
        <el-table-column prop="status" label="状态" width="110">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="提交时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" @click="openReview(row)">审核</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog v-model="showReviewDialog" title="项目审核" width="600px">
             <div class="review-info">
         <el-descriptions :column="1" border>
           <el-descriptions-item label="负责人">{{ reviewProject?.leaderName || '-' }}</el-descriptions-item>
           <el-descriptions-item label="项目名称">{{ reviewProject?.name }}</el-descriptions-item>
                       <el-descriptions-item label="项目种类">
              <el-tag :type="getProjectCategoryTagType(reviewProject?.projectCategory)" size="small">
                {{ getProjectCategoryName(reviewProject?.projectCategory || 'teaching') }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="项目类型">
              <el-tag :type="getProjectTypeTagType(reviewProject?.projectType)" size="small">
                {{ reviewProject?.projectType || '-' }}
              </el-tag>
            </el-descriptions-item>
           <el-descriptions-item label="项目级别">{{ reviewProject?.level }}</el-descriptions-item>
           <el-descriptions-item label="当前状态">{{ reviewProject?.status }}</el-descriptions-item>
         </el-descriptions>
       </div>
      <el-form :model="reviewForm" label-width="100px" style="margin-top: 20px;">
        <el-form-item label="审核结果" required>
          <el-radio-group v-model="reviewForm.status">
            <el-radio label="已通过">通过</el-radio>
            <el-radio label="已驳回">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" required>
          <el-input v-model="reviewForm.opinion" type="textarea" :rows="4" placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showReviewDialog = false">取消</el-button>
        <el-button type="primary" :loading="reviewLoading" @click="submitReview">提交审核</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getTeachingProjects } from '@/api/teachingProject'
import { getPendingReviewResearchProjects } from '@/api/researchProject'
import { getPendingAcademicAchievements } from '@/api/academicAchievement'
import http from '@/utils/request'

const loading = ref(false)
const filterStatus = ref('')
const filterProjectCategory = ref('teaching')
const projects = ref([])

// 审核相关
const showReviewDialog = ref(false)
const reviewProject = ref(null)
const reviewLoading = ref(false)
const reviewForm = reactive({ status: '', opinion: '' })

const formatDateTime = (v) => {
  if (!v) return '-'
  try { return new Date(v).toLocaleString('zh-CN') } catch { return '-' }
}

const getStatusType = (status) => {
  const types = { '申报中': 'info', '已立项': 'success', '执行中': 'warning', '结题审核中': 'warning', '已结题': 'success', '已驳回': 'danger', '延期': 'warning', '终止': 'danger' }
  return types[status] || 'info'
}

const getProjectCategoryTagType = (projectCategory) => {
  const types = {
    'teaching': 'primary',
    'research': 'success',
    'academic': 'warning'
  }
  return types[projectCategory] || 'primary'
}

const getProjectCategoryName = (projectCategory) => {
  const names = {
    'teaching': '教学项目',
    'research': '科研项目',
    'academic': '学术成果'
  }
  return names[projectCategory] || '教学项目'
}

const getProjectTypeTagType = (projectType) => {
  // 为原有的项目类型保留颜色配置
  const types = {
    '重点项目': 'danger',
    '一般项目': 'primary',
    '青年项目': 'success',
    '自筹项目': 'info'
  }
  return types[projectType] || 'info'
}

// 获取需要审核的项目
const fetchProjects = async () => {
  try {
    loading.value = true
    
    let projectList = []
    
    // 根据项目种类筛选不同的数据库
    switch (filterProjectCategory.value) {
      case 'teaching':
        // 搜索教学项目数据库
        const teachingResponse = await getTeachingProjects()
        projectList = Array.isArray(teachingResponse) ? teachingResponse : (teachingResponse?.data || [])
        // 为教学项目数据添加项目种类字段
        projectList = projectList.map(p => ({ ...p, projectCategory: 'teaching' }))
        break
        
      case 'research':
        // 搜索科研项目数据库
        const researchResponse = await getPendingReviewResearchProjects()
        projectList = Array.isArray(researchResponse) ? researchResponse : (researchResponse?.data || [])
        // 为科研项目数据添加项目种类字段
        projectList = projectList.map(p => ({ ...p, projectCategory: 'research' }))
        break
        
      case 'academic':
        // 搜索学术成果数据库
        const academicResponse = await getPendingAcademicAchievements()
        projectList = Array.isArray(academicResponse) ? academicResponse : (academicResponse?.data || [])
        // 为学术成果数据添加项目种类字段
        projectList = projectList.map(p => ({ ...p, projectCategory: 'academic' }))
        break
        
      default:
        // 默认搜索教学项目数据库
        const defaultResponse = await getTeachingProjects()
        projectList = Array.isArray(defaultResponse) ? defaultResponse : (defaultResponse?.data || [])
        // 为教学项目数据添加项目种类字段
        projectList = projectList.map(p => ({ ...p, projectCategory: 'teaching' }))
        break
    }
    
    // 只显示需要审核的项目
    const reviewProjects = projectList.filter(p => p.status === '申报中' || p.status === '结题审核中')
    
    // 按状态筛选
    let filteredProjects = reviewProjects
    if (filterStatus.value) {
      filteredProjects = filteredProjects.filter(p => p.status === filterStatus.value)
    }
    
    projects.value = filteredProjects
  } catch (e) {
    console.error(e)
    ElMessage.error('获取项目列表失败')
    projects.value = []
  } finally {
    loading.value = false
  }
}

// 打开审核对话框
const openReview = (row) => {
  reviewProject.value = row
  reviewForm.status = ''
  reviewForm.opinion = ''
  showReviewDialog.value = true
}

// 提交审核
const submitReview = async () => {
  try {
    if (!reviewForm.status || !reviewForm.opinion) {
      ElMessage.warning('请填写完整的审核信息')
      return
    }
    reviewLoading.value = true
    
    // 根据项目种类选择不同的API端点
    let apiUrl
    if (filterProjectCategory.value === 'research') {
      apiUrl = `/api/research-projects/${reviewProject.value.id}/review`
    } else if (filterProjectCategory.value === 'academic') {
      apiUrl = `/api/academic-achievements/${reviewProject.value.id}/review`
    } else {
      // 默认使用教学项目API
      apiUrl = `/api/projects/${reviewProject.value.id}/review`
    }
    
    await http.post(apiUrl, {
      status: reviewForm.status,
      opinion: reviewForm.opinion
    })
    ElMessage.success('审核完成')
    showReviewDialog.value = false
    fetchProjects()
  } catch (e) {
    console.error(e)
    ElMessage.error('审核失败')
  } finally {
    reviewLoading.value = false
  }
}

const handleFilterChange = () => {
  fetchProjects()
}

const clearFilters = () => {
  filterStatus.value = ''
  filterProjectCategory.value = 'teaching'
  fetchProjects()
}

onMounted(() => {
  fetchProjects()
})
</script>

<style scoped>
.review-center {
  max-width: 1400px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}
.page-title {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 500;
}
.header-actions {
  display: flex;
  align-items: center;
}
.filter-bar {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-summary {
  margin-left: auto;
}

.project-category-info {
  margin-bottom: 16px;
}
.review-info {
  margin-bottom: 20px;
}
</style>